package com.ml.loan.common.valid;

import com.google.common.collect.Sets;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Set;

/**
 * 是否存在数据集的校验器
 *
 * @Author caozx
 * @Date 2021/4/9 18:49
 **/
public class ListValueValidator implements ConstraintValidator<ListValue, Integer> {

    private boolean required = false;

    private Set<Integer> set = Sets.newHashSet();

    @Override
    public void initialize(ListValue constraintAnnotation) {
        required = constraintAnnotation.required();
        int[] value = constraintAnnotation.value();
        for (int v : value) {
            set.add(v);
        }
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) {
        if (value == null) {
            return !required;
        }
        return !set.isEmpty() && set.contains(value);
    }
}
